package org.onvivals.common.utils;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * FFmpegUtils
 *
 * @author weirdor (179946422@qq.com)
 * @version v1.0.0
 */
@Slf4j
public class FFmpegUtils {

    public static void waveMaker(String sourcePath, String targetPath) {
        Runtime run = null;
        Process p = null;
        try {
            run = Runtime.getRuntime();
            //-ac 1:声道数量转成1  -ar 16000:采样率转成16000Hz  -ab 32k:比特率转成32kb
            //格式通过targetPath后缀自动识别转换
			String command = "ffmpeg -i " + sourcePath + " -ac 1 -ar 16000 -b:a 32k -y " + targetPath;
            if (StrUtil.isBlank(command)) {
                return;
            }
            p = run.exec(command);
            p.waitFor();
            log.info("sourcePath:{} convert to targetPath:{} success", sourcePath, targetPath);
        } catch (Exception e) {
            log.error("msg=waveMaker异常：{}", e.getMessage(), e);
        } finally {
            try {
                p.getOutputStream().close();
                p.getInputStream().close();
                p.getErrorStream().close();
                run.freeMemory();
            } catch (IOException e) {
                log.error("msg=waveMaker异常：{}", e.getMessage(), e);
            }
        }
    }

}
